<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-06-21 17:05:24
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-07-18 16:12:14
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\EquipManage\PipnetLedger\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, watch, reactive, h, nextTick } from 'vue'
import { ElTree, ElInput, ElTag } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useEquipStore } from '@/store/modules/equip'
import { FacilityTypeList } from '@/api/equip/type'
import EditCofig from '../EquipType/components/EditCofig.vue'
import { Dialog } from '@/components/Dialog'
import PipnentInfoApi from '@/api/equip/pipnet'
import { flatData } from '@/hooks/PublicFun'
import { BaseButton } from '@/components/Button'
import EditPnLedgerType from './components/EditPnLedgerType.vue'
import { useGISStore } from '@/store/modules/gis'
const { t } = useI18n()
const ids = ref<string[]>([])
const GISStore = useGISStore()
const EquipStore = useEquipStore()
const treeEl = ref<typeof ElTree>() //树结构
const currentNodeKey = ref('') //树结构ID
const departmentList = ref<any>([]) //树结构数据
//表格内容接口
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const i = await PipnentInfoApi.GetpnLedgerList({
      pnId: unref(currentNodeKey),
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: i.rows,
      total: i.total
    }
  },
  fetchDelApi: async () => {
    const res = await PipnentInfoApi.DeletPnLedgerConfig(unref(ids)[0])
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const FormDisabled = ref(true)
//表格结构
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'pnId',
    label: t('管网片区'),
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return flatData(departmentList.value).map((item) => {
        if (item.id == cellValue) {
          return t(item.label)
        }
      })
    },
    form: {
      component: 'TreeSelect',
      colProps: {
        span: 20
      },
      componentProps: {
        renderAfterExpand: false,
        showCheckbox: true,
        checkStrictly: true,
        checkOnClickNode: true,
        data: departmentList,
        nodeKey: 'id',
        props: {
          label: 'label'
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'pnName',
    label: t('管网名称'),

    form: {
      component: 'Input',
      colProps: {
        span: 20
      }
    }
  },
  {
    field: 'pnType',
    label: t('管网类型'),
    width: 200,
    formatter: (_: Recordable, __: any, cellValue: number) => {
      return h(
        ElTag,
        {
          type: 'primary'
        },
        () => (cellValue == 1 ? t('参考官网') : t('正式运行'))
      )
    },
    form: {
      component: 'RadioGroup',
      colProps: {
        span: 20
      },
      componentProps: {
        options: [
          {
            label: '正式运行',
            value: 0
          },
          {
            label: '参考官网',
            value: 1
          }
        ]
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn" onClick={() => action(data.row, 'Edit')}>
                {t('修改')}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const fetchDepartment = async () => {
  const res = await PipnentInfoApi.GetPnTopologyTree()
  departmentList.value = res.data
  currentNodeKey.value = (res.data[0] && res.data[0].children && res.data[0].children[0].id) || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
}
fetchDepartment() //获取树结构
const currentDepartment = ref('') //树结构搜索框内容
watch(
  () => currentDepartment.value, //监控树结构搜索框内容变化
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  //树结构点击
  currentNodeKey.value = data.id
  currentPage.value = 1 //页面为第一页
  getList() //表格更新
}
const filterNode = (value: string, data: any) => {
  //树结构变化
  if (!value) return true
  return data.label.includes(value)
}
const currentRow = ref<FacilityTypeList>()
const saveLoading = ref(false)
const delLoading = ref(false)
//表格删除操作
const delData = async (row: FacilityTypeList | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: any) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const EditCofigRef = ref()
const EditTypeRef = ref()
const SureCompont = ref('') //确认打开弹窗为类型修改还是配置表单
const actionType = ref('')
const facilityType = ref('')
const SubmitConfig = async () => {
  const write = unref(EditCofigRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (actionType.value == 'add') {
      res.value = await PipnentInfoApi.AddPnLedgerConfig(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await PipnentInfoApi.EditPnLedgerConfig(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      GISStore.setPnLedgerList() //其他页面获取管网信息
      getList()
    }
  }
}
const SubmitType = async () => {
  const write = unref(EditTypeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    //新增任务组
    if (facilityType.value == 'add') {
      res.value = await PipnentInfoApi.AddPnTopology(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改字
      res.value = await PipnentInfoApi.EditPnTopology(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      fetchDepartment() //获取树结构
      currentPage.value = 1
      getList()
    }
  }
}
const save = () => {
  if (SureCompont.value == 'Config') {
    SubmitConfig()
  } else {
    SubmitType()
  }
}
//表格中操作
const action = (row: FacilityTypeList, type: string) => {
  SureCompont.value = 'Config'
  actionType.value = type
  dialogVisible.value = true //打开弹窗
  if (type == 'add') {
    dialogTitle.value = '新增'
    FormDisabled.value = false
    currentRow.value = {}
  } else if (type == 'Edit') {
    dialogTitle.value = '修改'
    FormDisabled.value = false
    currentRow.value = row
  } else if (type == 'Detail') {
    dialogTitle.value = '查看'
    FormDisabled.value = true
    currentRow.value = row
  }
}
//类型中操作
const EditTypeTree = async (type: string) => {
  SureCompont.value = 'Type'
  if (type == 'delete') {
    const res = await PipnentInfoApi.DeletPnTopology(currentNodeKey.value)
    if (res) {
      fetchDepartment() //获取树结构
      currentPage.value = 1 //页面为第一页
      getList() //表格更新
    }
  } else if (type == 'edit') {
    EquipStore.setPnTopologyDetail(currentNodeKey.value)
    dialogVisible.value = true //打开弹窗
    facilityType.value = type
  } else {
    EquipStore.PnTopologyDetail = { parentId: Number(currentNodeKey.value) }
    dialogVisible.value = true //打开弹窗
    facilityType.value = type
  }
}
</script>
<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px min-h-[580px]" title="管网拓扑">
      <div class="flex justify-around mb-[10px]">
        <BaseButton type="primary" size="small" @click="EditTypeTree('add')">新增</BaseButton>
        <BaseButton type="primary" size="small" @click="EditTypeTree('edit')">修改</BaseButton>
        <BaseButton type="danger" size="small" @click="EditTypeTree('delete')">删除</BaseButton>
      </div>
      <ElInput
        v-model="currentDepartment"
        class="flex-[2] mb-[10px]"
        :placeholder="t('组织名称')"
        clearable
      />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'departmentName'
        }"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.label" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.label }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px" title="管线台账">
      <!-- <div class="flex"> -->
      <BaseButton size="small" type="primary" @click="action({}, 'add')" class="AddbtnStyle">
        <Icon icon="ep:plus" :size="13" />新增管网
      </BaseButton>
      <!-- </div> -->
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>
    <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 500px" maxHeight="400px">
      <EditCofig
        ref="EditCofigRef"
        v-if="SureCompont == 'Config'"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
        :FormDisabled="FormDisabled"
      />
      <EditPnLedgerType ref="EditTypeRef" v-else :current-row="EquipStore.PnTopologyDetail" />
      <template #footer v-if="actionType !== 'Detail'">
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style scope>
/* .el-tree {
  height: 410px;
  overflow: hidden;
  overflow-y: scroll;
} */
.el-tree-node:focus > .el-tree-node__content {
  color: #409eff;
}
.el-card__body {
  padding: 10px;
  /* height: 90%; */
}
.CloseBtn {
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
.AddbtnStyle {
  margin-bottom: 18px;
  margin-right: 10px;
}
.el-collapse-item {
  padding: 15px 0;
}
.el-collapse-item__content {
  padding-bottom: 0;
}
.el-collapse-item__header {
  width: 62px;
  height: 24px;
  border-radius: 2px;
  color: white;
  background: #409eff;
  justify-content: center;
  font-size: 12px;
}
.el-collapse-item__arrow {
  margin: 0 2px;
}

.TableBtn {
  margin: 0 5px;
  cursor: pointer;
  color: #409eff;
  font-weight: 600;
}
</style>
